package com.kangfu.api.controller;

import com.kangfu.api.interceptor.AuthorizationInterceptor;
import com.kangfu.api.service.IAddressService;
import com.kangfu.common.model.AjaxResult;
import com.kangfu.db.domain.entity.Address;
import com.kangfu.db.model.request.AddressRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotBlank;
import java.util.List;

@RestController
@RequestMapping("/address")
@Validated
public class AddressController {

    @Autowired
    public IAddressService addressService;

    @PostMapping("/add")
    public AjaxResult add(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId, @Valid @RequestBody AddressRequest addressRequest) {
        addressService.insertAddress(userId, addressRequest);
        return AjaxResult.success();
    }

    @GetMapping("/list")
    public AjaxResult list(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId, @Max(value = 5, message = "最大值为5") @RequestParam(name = "page", defaultValue = "1")  int page) {
        List<Address> list = addressService.getAddressList(userId, page);
        return AjaxResult.success(list);
    }

    @GetMapping("/info/{id}")
    public AjaxResult info(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId, @PathVariable int id) {
        Address address = addressService.getAddress(userId, id);
        return AjaxResult.success(address);
    }

    @PostMapping("/update/{id}")
    public AjaxResult update(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId,@PathVariable int id, @RequestBody AddressRequest addressRequest) {
        addressService.updateAddress(userId, id, addressRequest);
        return AjaxResult.success();
    }

    @PostMapping("/del/{id}")
    public AjaxResult del(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId,@PathVariable int id) {
        addressService.delAddress(userId, id);
        return AjaxResult.success();
    }

}
